package com.lmm.lcbusiness.lcbusiness.jsbridge;

import android.annotation.TargetApi;
import android.os.Build;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * Created by chenliang on 2016/12/6.
 */
public class THJSWebViewBridge {

    public static final String CALLBACK_JSSUCCESS_FORMAT = "javascript:H5App.onSuccess('%s','%s');";
    public static final String CALLBACK_JSFAILURE_FORMAT = "javascript:H5App.onFailure('%s','%s');";

    private WebView webView;

    private Map<String, THJSWebViewBridgeCall> handlers = new HashMap<String, THJSWebViewBridgeCall>();

    public interface THJSWebViewBridgeCall {
        void call(THJSWebViewBridgeAction action);
    }

    public void callJsBack(String port, boolean status, String data) {
        String callFormate = status ? CALLBACK_JSSUCCESS_FORMAT : CALLBACK_JSFAILURE_FORMAT;
        final String callbackJs = String.format(Locale.getDefault(), callFormate, port, data);
        executeJavascript(callbackJs);
    }

    public THJSWebViewBridge(WebView webView) {
        this.webView = webView;
        this.webView.addJavascriptInterface(new h5interface(), "H5Native");
    }

    public void register(String method, THJSWebViewBridgeCall cljsWebViewBridgeCall) {
        handlers.put(method, cljsWebViewBridgeCall);
    }

    public void handleActions(List<THJSWebViewBridgeAction> actions) {
        for (THJSWebViewBridgeAction action : actions) {
            THJSWebViewBridgeCall thjsWebViewBridgeCall = handlers.get(action.getMethod());
            thjsWebViewBridgeCall.call(action);
        }
    }

    class h5interface {
        /**
         * Show a toast from the web page
         */
        @JavascriptInterface
        public void callNative(String event, final String port, String params) {
            try {
                JSONObject jsparams = null;
                if (!params.equals("undefined") && params != "undefined") {
                    jsparams = new JSONObject(params);
                }

                List<THJSWebViewBridgeAction> actions = new ArrayList<>();

                THJSWebViewBridgeAction action = new THJSWebViewBridgeAction();
                action.setMethod(event);
                action.setData(jsparams);
                action.setPort(port);

                actions.add(action);

                handleActions(actions);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void executeJavascript(final String script) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWebView().post(new Runnable() {
                @TargetApi(Build.VERSION_CODES.KITKAT)
                @Override
                public void run() {
                    webView.evaluateJavascript(script, new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {

                        }
                    });
                }
            });
        } else {
            getWebView().post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl(script);
                }
            });
        }
    }

    public WebView getWebView() {
        return webView;
    }

    public void setWebView(WebView webView) {
        this.webView = webView;
    }

}
